#include <QtCore/QString>
#include <QtTest/QtTest>
#include <QDebug>
#include <stdlib.h>
#include "Group.h"
#include "Contact.h"
#include "SymmetricKeyInfo.h"
#include "ContactsManager.h"
#include "DatabaseManagerException.h"
#include "KeyInfo.h"
#include "KeyManager.h"
#include "KeyGenerator.h"
#include "DatabaseManager.h"

using namespace kryptos::cryptography;
using namespace kryptos::entities;
using namespace kryptos::database;

class ContactsManagerTest : public QObject
{
    Q_OBJECT

public:
    ContactsManagerTest(){}

private Q_SLOTS:

    void addContactsToDefaultGroup();

    void initTestCase();
    void cleanupTestCase();

private:

};

void ContactsManagerTest::initTestCase()
{
    QFile::remove("kryptos_groups.k");
    QFile::remove("kryptos_keyring.k");
    KeyGenerator::init();
    DatabaseManager::manager().openKeyring();
}

void ContactsManagerTest::addContactsToDefaultGroup()
{
    try
    {
        KeyInfo info(KeyInfo::RSA, "sebastian", "seba@gmail.com", "testing", "sebsatian", 1024);

        PrivateKey privateKey = KeyGenerator::generateEncodedKey(info, KeyInfo::RSA);
        info.setKeyid(KeyGenerator::generateKeyId(privateKey));
        info.setPassphrase(QCryptographicHash::hash(QByteArray(info.passphrase().c_str()), QCryptographicHash::Sha1).data());
        info.setTimestamp(QDate::currentDate().toString().toStdString());

        DatabaseManager::manager().addKeyPair(info, privateKey.key(), privateKey.publicKeyPart().key());

        Contact contact(info);
        ContactsManager::manager().addContactWithoutGroup(contact);

        GroupList list = ContactsManager::manager().allGroups();
        QVERIFY2(list.size() == 1, "Should have only default group");
        QCOMPARE(((Group)list.front()).name(), std::string("default"));

        Contact member = ((Group)list.front()).members().front();
        KeyInfo info2 = member.keyInfo();

        QCOMPARE(info2.name(), info.name());
        QCOMPARE(info2.email(), info.email());
        QCOMPARE(info2.comment(), info.comment());
        QCOMPARE(info2.passphrase(), info.passphrase());
        QCOMPARE(info2.size(), info.size());
    }
    catch (DatabaseManagerException& e)
    {
        QFAIL("Error adding contact to default group");
    }
}

void ContactsManagerTest::cleanupTestCase()
{
}

QTEST_MAIN(ContactsManagerTest);

#include "ContactsManagerTest.moc"
